import Vue from "vue";
import Router from "vue-router";
import website from "./website";
import account from "./account";
import shop from "./shop";
import token from "../utils/token";
import $store from "../store";
import { addLoading, delLoading } from "@/utils/loading";

const getEdit = pageName => resolve =>
  require(["../views/main/edit"], page => resolve(page[pageName]));

Vue.use(Router);
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    website,
    account,
    shop,
    {
      path: "/step1",
      name: "step1",
      component: getEdit("step1"),
      meta: "main"
    },
    {
      path: "/step2",
      name: "step2",
      component: getEdit("step2"),
      meta: "main"
    },
    {
      path: "/step3",
      name: "step3",
      component: getEdit("step3"),
      meta: "main"
    }
  ]
});

router.beforeEach((to, from, next) => {
  let tokens = token.getCookie("_token");
  addLoading();
  if (to.matched.length == 0) {
    next({
      path: "/notFind"
    });
  }
  $store.state.imgInitPgae = 1;
  if (!to.name && !from.name) {
    next({
      path: "/step1"
    });
  }
  if (!tokens) {
    $store.state._token = "";
    if (to.meta === "main") {
      next({
        path: "/login"
      });
    }
  } else {
    if (to.name === "login") {
      next({
        path: "/"
      });
    }
  }
  next();
});
router.afterEach(() => {
  delLoading();
});
export default router;
